//
//  TTOrderDetailShopViewCell.m
//  TaoTuo
//
//  Created by admin on 2019/10/9.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTOrderDetailShopViewCell.h"
#import "TTOrderShopModel.h"
#import "TTOrderGoodsViewCell.h"
#import "TTLuoshiViewCell.h"
#import "TTOrderDetailModel.h"
#import "TTChangeHandSizePopView.h"
#import "TTGoodsDetailViewController.h"
#import "TTShopCartSubDetailModel.h"
#import "TTDiamondPopListView.h"
#import "TTMessageViewController.h"

static NSString *cellID = @"goods_cell_id";
static NSString *luoshiCellID = @"luoshi_cell_id";

@interface TTOrderDetailShopViewCell ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UIView *bgView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *dataArray;
@property (nonatomic, assign) int orderType;
@property (nonatomic, assign) int orderStatus;
@property (nonatomic, copy) NSString *goodsCertType;
@property (nonatomic, strong) NSDictionary *typeDic;

@property (nonatomic, strong) TTOrderDetailModel *detailModel;

@end

@implementation TTOrderDetailShopViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        self.typeDic = @{
            @"10" : @"现货",
            @"20" : @"定制",
            @"30" : @"裸石"
        };
        
        
    }
    return self;
}

- (void)setDataArray:(NSArray *)dataArray orderType:(int)orderType goodsCertType:(NSString *)goodsCertType detailModel:(nonnull TTOrderDetailModel *)detailModel
{
    self.detailModel = detailModel;
    self.orderStatus = detailModel.OrderState.intValue;
    
    [self setDataArray:dataArray orderType:orderType goodsCertType:goodsCertType];
}

- (void)setDataArray:(NSArray *)dataArray orderType:(int)orderType goodsCertType:(nonnull NSString *)goodsCertType
{
    self.dataArray = dataArray;
    self.orderType = orderType;
    self.goodsCertType = goodsCertType;
    
    CGFloat H = 0;
    for (NSArray *arr in dataArray) {
        for (TTOrderShopModel *shopModel in arr) {
            H += shopModel.h;
        }
    }
    H += 40;
    if (dataArray.count > 1) {
        H += 30;
    }
    
    self.bgView.frame = CGRectMake(5, 5, SCREEN_WIDTH - 10, H - 10);
    self.tableView.frame = self.bgView.bounds;
    
    self.bgView.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:self.bgView.bounds cornerRadius:5].CGPath;
    
    [self addHeaderView];
    
    [self.tableView reloadData];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *arr = self.dataArray[section];
    return arr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *arr = self.dataArray[indexPath.section];
    TTOrderShopModel *model = arr[indexPath.row];
    NSArray *firstArray = self.dataArray.firstObject;
    if (model.GoodsType == 1) {
        // 裸石
        TTLuoshiViewCell *cell = [tableView dequeueReusableCellWithIdentifier:luoshiCellID];
        [cell setModel:model hasShadow:NO isGray:![firstArray containsObject:model] isFromOrderDetail:YES orderStatus:self.orderStatus];
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    } else {
        TTOrderGoodsViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        [cell setModel:model hasShadow:NO isGray:![firstArray containsObject:model]];
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTOrderShopModel *model = self.dataArray[indexPath.section][indexPath.row];
    if (model.GoodsType != 1) {
        TTGoodsDetailViewController *detailVC = [[TTGoodsDetailViewController alloc] initWithStyleLibraryId:model.StyleLibraryId model:nil];
//        detailVC.styleLibraryId = model.StyleLibraryId;
        [[LLRouteTool getCurrentNavigationController] pushViewController:detailVC animated:YES];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *arr = self.dataArray[indexPath.section];
    TTOrderShopModel *model = arr[indexPath.row];
    return model.h;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        return 22;
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.width, 22)];
        UILabel *label = [UILabel labelWithTitle:@"被镶嵌商品" color:UIColorHex(999999) fontSize:12];
        label.frame = CGRectMake(10, 0, 200, view.height);
        [view addSubview:label];
        
        [LLLineUtilies addLineInView:view startPoint:CGPointMake(10, 0) endPoint:CGPointMake(view.width - 10, 0) lineColor:kSeparatorColor];
        
        return view;
    }
    
    return [UIView new];
}

///请求改手寸接口
- (void)gotoChangeHandSize:(int)handSize
{
    TTOrderShopModel *model = self.detailModel.Detail.firstObject;
    NSDictionary *dic = @{
        @"param.wholesalerName" : [TTLoginSingle sharedSingle].loginModel.RealName,
        @"param.orderNo" : self.detailModel.OrderNo,
        @"param.goodsBarCode" : model.GoodsBarCode,
        @"param.updateHandSize" : @(handSize),
        @"param.orderUpdateHandSizePrice" : @(30)
    };
    [[LLNetworkManagerTool sharedManager] postUrlString:updateHandSize_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"handSizeChangeSuccessNotify_key" object:nil];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:self.viewController.view];
}

///确定改手寸的弹窗
- (void)confirmChangeHandSize:(int)handSize
{
    NSString *str = [NSString stringWithFormat:@"确定要将%d#手寸改成%d#吗？", self.detailModel.HandSize, handSize];
    @weakify(self)
    LLSystemAlertView *alertView = [LLSystemAlertView alertViewWithTitle:@"改手寸" message:str cancelTitle:@"取消" cancelBlock:nil confirmTitle:@"确定" confirmBlock:^BOOL{
        @strongify(self)
        [self gotoChangeHandSize:handSize];
        return YES;
    }];
    
//    [alertView showInView:nil animationDuration:0];
    [alertView showInWindowWithBackgoundTapDismissEnable:YES];
}

///改手寸的弹窗
- (void)changeHandSizeAction
{
    if (self.detailModel.UpdateHandSize > 0) {
        return;
    }
    @weakify(self)
    TTChangeHandSizePopView *popView = [TTChangeHandSizePopView changeHandSizeViewWithCurrentHandSize:self.detailModel.HandSize selectBlock:^(int handSize) {
        @strongify(self)
        [self confirmChangeHandSize:handSize];
    }];
    [TYShowAlertView showAlertViewWithView:popView backgoundTapDismissEnable:YES];
}

///给空托或裸石镶嵌
- (void)insetBtnClick
{
    NSString *insertSize = @"";
    TTOrderShopModel *model = self.detailModel.Detail.firstObject;
    if (self.detailModel.GoodsType == 1) {
        // 裸石
        insertSize = [NSString stringWithFormat:@"%d", [TTLoginSingle findDiamondSizeWithSize:model.DiaSize.floatValue * 100]];
    } else {
        insertSize = model.GoodsInsertSize;
    }
    
    NSDictionary *dic = @{
        @"param.inlayGoodsType" : @(self.detailModel.GoodsType),
        @"param.insertSize" : insertSize,
        @"param.pageIndex" : @1,
        @"param.pageSize" : @40
    };
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:getOrderInlayList_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        NSMutableArray *array = [NSMutableArray array];
        for (NSDictionary *dic in responseObject) {
            TTShopCartSubDetailModel *sdmodel = [TTShopCartSubDetailModel modelWithJSON:dic];
            sdmodel.Status = @"1";
            sdmodel.Cert = dic[@"GoodsCertType"];
            sdmodel.CertNo = dic[@"GoodsCertNo"];
            sdmodel.CertPic = dic[@"GoodsCertPic"];
            if (dic[@"DiaSize"] == nil || [dic[@"DiaSize"] isKindOfClass:[NSNull class]]) {
                sdmodel.DiaSize = model.DiaSize;
            }
            if (sdmodel.GoodsType == 1) {
                sdmodel.GoodsDescribe = @[dic[@"GoodsDescribe"]];
                sdmodel.h = 65 * kScale + 40;
            } else {
                NSString *str = dic[@"GoodsDescribe"];
                NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
                NSArray *arr = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                NSString *content = [arr componentsJoinedByString:@"\n"];
                sdmodel.GoodsDescribe = @[content];
                CGFloat w = SCREEN_WIDTH - 105 * kScale - 55;
                CGFloat h = [content boundingRectWithSize:CGSizeMake(w, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:12]} context:nil].size.height;
                sdmodel.h = h + 80;
            }
            [array addObject:sdmodel];
        }
        if (array.count == 0) {
            //没有匹配到裸石
            NSString *hintTitle = self.detailModel.GoodsType == 1 ? @"没有匹配到空托" : @"没有匹配到裸石";
            NSString *message = self.detailModel.GoodsType == 1 ? @"该裸石没有匹配到空托" : @"该空托没有匹配到裸石";
            @weakify(self)
            LLSystemAlertView *alertView = [LLSystemAlertView alertViewWithTitle:hintTitle message:message cancelTitle:@"取消" cancelBlock:nil confirmTitle:@"去购买" confirmBlock:^BOOL{
                @strongify(self)
                NSInteger index = self.detailModel.GoodsType == 1 ? 0 : 1;
                
                TTMessageViewController *messageVC = [[TTMessageViewController alloc] init];
                messageVC.defaultSelectIndex = index;
                [[LLRouteTool getCurrentNavigationController] pushViewController:messageVC animated:YES];
                
                return YES;
            }];
            [alertView showInWindowWithBackgoundTapDismissEnable:YES];
        } else {
            TTDiamondPopListView *popView = [TTDiamondPopListView popListViewWithDataArray:array];
            [popView showInView:nil animationDuration:0.5];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"needInlayLuoshiOrKongtuo_key" object:array.firstObject];
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:self.viewController.view];
    
}


- (void)addHeaderView
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.width, 38)];
    
    NSString *title = self.typeDic[[NSString stringWithFormat:@"%d", self.orderType]];
    UILabel *titleLabel = [UILabel labelWithTitle:title color:[UIColor blackColor] fontSize:15];
    UIButton *scBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [scBtn addTarget:self action:@selector(changeHandSizeAction) forControlEvents:UIControlEventTouchUpInside];
    scBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    
    UIButton *checkBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [checkBtn setImage:[UIImage imageNamed:@"goujian"] forState:UIControlStateNormal];
    [checkBtn setTitleColor:UIColorHex(666666) forState:UIControlStateNormal];
    checkBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    
    UIButton *insetBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    insetBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    
    UIStackView *stView = [[UIStackView alloc] initWithFrame:CGRectMake(10, 0, view.width - 20, view.height)];
    stView.axis = UILayoutConstraintAxisHorizontal;
    stView.distribution = UIStackViewDistributionFill;
    stView.alignment = UIStackViewAlignmentCenter;
    stView.spacing = 10;
    [view addSubview:stView];
    
    [stView addArrangedSubview:titleLabel];
    //改手寸
    if (self.detailModel.OrderState.intValue < 60 && self.detailModel.IsChangeHand) {
        [stView addArrangedSubview:scBtn];
        if (self.detailModel.UpdateHandSize == 0) {
            [scBtn setImage:[UIImage imageNamed:@"bianji"] forState:UIControlStateNormal];
            [scBtn setTitle:@"改手寸" forState:UIControlStateNormal];
            [scBtn setTitleColor:kMainColor forState:UIControlStateNormal];
        } else {
            [scBtn setImage:[UIImage imageNamed:@"goujian"] forState:UIControlStateNormal];
            [scBtn setTitleColor:UIColorHex(666666) forState:UIControlStateNormal];
            NSString *scTitle = [NSString stringWithFormat:@"改%d#", self.detailModel.UpdateHandSize];
            [scBtn setTitle:scTitle forState:UIControlStateNormal];
        }
    }
    //是否需镶嵌
    if (self.detailModel.OrderType == 10 || self.detailModel.OrderType == 20) {
        //现货或定制
        if (!self.detailModel.IsFinishedProduct && !self.detailModel.OrderIsInlay && self.detailModel.OrderState.intValue <= 60) {
            [insetBtn setImage:[UIImage imageNamed:@"bianji"] forState:UIControlStateNormal];
            [insetBtn setTitle:@"需镶嵌" forState:UIControlStateNormal];
            [insetBtn setTitleColor:kMainColor forState:UIControlStateNormal];
            [insetBtn addTarget:self action:@selector(insetBtnClick) forControlEvents:UIControlEventTouchUpInside];
        } else {
            [insetBtn setImage:[UIImage imageNamed:@"goujian"] forState:UIControlStateNormal];
            [insetBtn setTitle:@"镶嵌服务" forState:UIControlStateNormal];
            [insetBtn setTitleColor:UIColorHex(666666) forState:UIControlStateNormal];
        }
    } else {
        // 裸石
        if (!self.detailModel.OrderIsInlay && self.detailModel.OrderState.intValue <= 60) {
            [insetBtn setImage:[UIImage imageNamed:@"bianji"] forState:UIControlStateNormal];
            [insetBtn setTitle:@"需镶嵌" forState:UIControlStateNormal];
            [insetBtn setTitleColor:kMainColor forState:UIControlStateNormal];
            [insetBtn addTarget:self action:@selector(insetBtnClick) forControlEvents:UIControlEventTouchUpInside];
        } else {
            [insetBtn setImage:[UIImage imageNamed:@"goujian"] forState:UIControlStateNormal];
            [insetBtn setTitle:@"镶嵌服务" forState:UIControlStateNormal];
            [insetBtn setTitleColor:UIColorHex(666666) forState:UIControlStateNormal];
        }
    }
    
    if (self.goodsCertType.length > 0) {
        [checkBtn setTitle:self.goodsCertType forState:UIControlStateNormal];
        [stView addArrangedSubview:checkBtn];
    }
    
    if (insetBtn.titleLabel.text.length > 0) {
        [stView addArrangedSubview:insetBtn];
    }
    
    [LLLineUtilies addLineInView:stView startPoint:CGPointMake(0, stView.height) endPoint:CGPointMake(stView.width, stView.height) lineColor:kSeparatorColor];
    
    self.tableView.tableHeaderView = view;
}


- (UIView *)bgView
{
    if (!_bgView) {
        _bgView = [[UIView alloc] init];
        _bgView.backgroundColor = [UIColor whiteColor];
        [self.contentView addSubview:_bgView];
        // 阴影
        _bgView.backgroundColor = [UIColor whiteColor];
        _bgView.layer.cornerRadius = 10;
        _bgView.layer.shadowColor = kMainColor.CGColor;
        _bgView.layer.shadowOffset = CGSizeZero;
        _bgView.layer.shadowOpacity = 0.2;
        
    }
    return _bgView;
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.scrollEnabled = NO;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableFooterView = [UIView new];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[TTOrderGoodsViewCell class] forCellReuseIdentifier:cellID];
        [_tableView registerClass:[TTLuoshiViewCell class] forCellReuseIdentifier:luoshiCellID];
        [self.bgView addSubview:_tableView];
    }
    return _tableView;
}



@end
